/**
 * @author jprieur
 */
package mygui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;

import results.*;
import kernel.*;
import objects.*;

public class ActionPlay extends AbstractAction {
	 
    private MonIHM _ihm;
    protected static File tmp_file = null;

    public ActionPlay(MonIHM ihm)
    {
	_ihm = ihm;
	putValue(AbstractAction.NAME,"Launch");
	putValue(AbstractAction.SHORT_DESCRIPTION,"Launch the simulation");
	putValue(AbstractAction.ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,KeyEvent.CTRL_MASK));
	putValue(AbstractAction.SMALL_ICON,UIM.createImageIcon("images/start.png","Start"));
    }
	 
    public void actionPerformed(ActionEvent arg) 
    {
	if(_ihm._kernel.getState() == Simulator.INIT){
	    try {
		tmp_file = File.createTempFile("tmp", "simmobil");
		BufferedWriter bw = new BufferedWriter(new FileWriter(tmp_file));
		//bw.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n<!DOCTYPE simmobil SYSTEM \"simmobil.dtd\">\n");
		bw.write(Simulator.getSimulator().xmlDump());
		bw.write("\n</simmobil>");
		bw.close();
	    }catch(IOException x){
		tmp_file = null;
		System.out.println(x);
	    }
	    
	    _ihm._display.setMode(DisplayPanel.Mode.SIMULATION);
	    
	    MonitorPanel monitor = _ihm.getMonitor();
	    if(Simulator.getSimulator().getMode() == Simulator.SENSOR){
		SensorSimulator kernel = (SensorSimulator)Simulator.getSimulator();
		for(SensorNetwork network : kernel.getSensorNetworkVector())
		    monitor.addObject(network);
		for(Sink sink : kernel.getSinkVector())
		    monitor.addObject(sink);
	    }else{
		Simulator kernel = Simulator.getSimulator();
		for(MobileStation station : kernel.getMobileStation())
		    monitor.addObject(station);
		Vector<BaseStation> bases = kernel.getBaseStation();
		for(BaseStation base : kernel.getBaseStation())
		    monitor.addObject(base);
	    }
	    Simulator kernel = Simulator.getSimulator();
	    ResultManager manager = kernel.getResultManager();
	    
	    for(Probe probe : manager.getProbeCom())
		monitor.distributeProbe(probe);
	    for(Probe probe : manager.getProbeDepl())
		monitor.distributeProbe(probe);

	    _ihm._kernel.runSim();
	}else if(_ihm._kernel.getState() == Simulator.PAUSE){
	    _ihm._kernel.replaySim();
	}
	_ihm.updateCommandes();

	_ihm._display.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

	//if ((_ihm._kernel.getMode()) == Simulator.ADHOC)
	    //_ihm.informationPane.routingPane.setVisible(true);
    }
}